<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任职职务" prop="position">
        <el-input
          v-model="queryParams.position"
          placeholder="请输入任职职务"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属公司" prop="company">
        <el-input
          v-model="queryParams.company"
          placeholder="请输入所属公司"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="行业" prop="categoryId">
        <el-select v-model="queryParams.categoryId" filterable clearable>
          <el-option v-for="(item, key) in categoryOptions" :key="key" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="my_main">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['article:talent:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['article:talent:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['article:talent:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="info"
              plain
              icon="Upload"
              @click="handleImport"
              v-hasPermi="['article:talent:import']"
          >导入</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['article:talent:export']"
          >导出</el-button>
        </el-col> -->
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" border :data="talentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="头像" align="center" prop="avatar">
          <template #default="{row}">
            <image-preview :src="row.avatar" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="任职职务" align="center" prop="position" width="200"/>
        <el-table-column label="所属公司" align="center" prop="company" width="200"/>
        <el-table-column label="所属行业" align="center" prop="industry" width="200">
          <template #default="{ row }">
            {{ getCategoryName(row) }}
          </template>
        </el-table-column>
        <el-table-column label="所属地域" align="center" prop="region">
          <template #default="{ row }">
            {{ row.region ? row.region.replaceAll(',', '') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="政策标签" align="center" prop="tagList">
          <template #default="{ row }">
            <div class="my_tags">
              <el-tag v-for="(item, key) in row.tagList" :key="key" type="primary">{{ item.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="专长介绍" align="center" prop="expertiseIntroduction" :show-overflow-tooltip="true" />
        <el-table-column label="个人介绍" align="center" prop="personalIntroduction" :show-overflow-tooltip="true" />
        <el-table-column label="申请状态" align="center" prop="status" width="100">
          <template #default="{row}">
              <el-tag :type="getStatusType(row)">{{ getStatus(row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="createTime" width="160"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260px">
          <template #default="scope">
            <el-button link type="success" icon="Edit" @click="handleAudit(scope.row)" v-hasPermi="['article:talent:audit']">审核</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['article:talent:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['article:talent:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改人才库对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="talentRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="12">
            <el-form-item label="头像" prop="avatar">
              <ImageUpload v-model="form.avatar" :limit="1" :isShowTip="false"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="任职职务" prop="position">
              <el-input v-model="form.position" placeholder="请输入任职职务" />
            </el-form-item>
            <el-form-item label="所属行业" prop="categoryIds">
              <el-select v-model="form.categoryIds" multiple collapse-tags filterable>
                <el-option v-for="(item, key) in categoryOptions" :key="key" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="12">
            <el-form-item label="人才标签" prop="tagIds">
              <el-select v-model="form.tagIds" filterable clearable multiple collapse-tags>
                <el-option v-for="(item, key) in tagOptions" :key="key" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属公司" prop="company">
              <el-input v-model="form.company" placeholder="请输入所属公司" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="所属地域" prop="regions">
          <!-- <el-input v-model="form.expertiseIntroduction" type="textarea" placeholder="请输入内容" /> -->
          <el-cascader v-model="form.regions" :options="cityOptions" :props="{ label: 'name', value: 'name', checkStrictly: true, emitPath: false }" filterable clearable show-all-levels />
        </el-form-item>
        <el-form-item label="专长介绍" prop="expertiseIntroduction">
          <el-input v-model="form.expertiseIntroduction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="个人介绍" prop="personalIntroduction">
          <el-input v-model="form.personalIntroduction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="审核" v-model="isAuidt" width="400px" append-to-body>
      <el-form ref="talentRef" :model="auditForm" label-width="80px">
        <el-select v-model="auditForm.status" filterable clearable style="width: 100%;">
          <el-option v-for="(item, key) in auditOptions" :key="key" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAuditForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
     <!-- 导入对话框 -->
     <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <!-- <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  </div> -->
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
               </div>
            </template>
         </el-upload>
         <template  #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
  </div>
</template>

<script setup name="Talent">
import { getToken } from "@/utils/auth";
import { listTalent, getTalent, delTalent, addTalent, updateTalent, auditTalent } from "@/api/article/talent";
import { listOptionsTag } from '@/api/article/tag';
import { listOptionsCategory } from "@/api/article/category";
import { listAllCityWithChildren } from '@/api/system/city'
const { proxy } = getCurrentInstance();
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/article/talent/importData"
});
const talentList = ref([]);
const open = ref(false);
const isAuidt = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const tagOptions = ref([])
const categoryOptions = ref([])
const auditOptions = ref([
  { label: '待审核', value:  'NOT_AUDIT'},
  { label: '审核通过', value: 'AUDIT' },
  { label: '审核驳回', value: 'REJECT' },
])
const cityOptions = ref([])
const data = reactive({
  form: {},
  auditForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    avatar: null,
    name: null,
    position: null,
    company: null,
    industry: null,
    expertiseIntroduction: null,
    personalIntroduction: null,
    status: null,
    isDeleted: null
  },
  rules: {
  }
});

const { queryParams, form, rules, auditForm } = toRefs(data);

function getCategoryName(row) {
  return row.categoryList ? row.categoryList.map(item => item.name).join(',') : ''
}
function importTemplate() {
  proxy.download("article/talent/importTemplate", {
  }, `talent_template_${new Date().getTime()}.xlsx`);
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "人才导入";
  upload.open = true;
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
/** 查询人才库列表 */
function getList() {
  loading.value = true;
  listTalent(queryParams.value).then(response => {
    talentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  isAuidt.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    avatar: null,
    name: null,
    position: null,
    company: null,
    industry: null,
    expertiseIntroduction: null,
    personalIntroduction: null,
    status: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    isDeleted: null,
    categoryIds: []
  };
  auditForm.value = {
    id: null,
    status: 0
  }
  proxy.resetForm("talentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  listOptions();
  open.value = true;
  title.value = "添加人才库";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  listOptions();
  const _id = row.id || ids.value
  getTalent(_id).then(response => {
    form.value = response.data;
    if (form.value.region) {
      form.value.regions = form.value.region.split(',')
    }
    form.value.tagIds = form.value.tagList ? form.value.tagList.map(item => item.id) : []
    form.value.categoryIds = form.value.categoryList ? form.value.categoryList.map(item => item.id) : []
    open.value = true;
    title.value = "修改人才库";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["talentRef"].validate(valid => {
    if (valid) {
      const tagList = []
      if (form.value.tagIds) {
        form.value.tagIds.map(id => {
          tagList.push({
            id: id
          })
        })
      }
      form.value.tagList = tagList
      const categoryList = []
      if (form.value.categoryIds) {
        form.value.categoryIds.map(id => {
          categoryList.push({
            id: id
          })
        })
      }
      form.value.categoryList = categoryList
      if (form.value.regions) {
        form.value.region = form.value.regions.join(',')
      }
      if (form.value.id != null) {
        updateTalent(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTalent(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除人才库编号为"' + _ids + '"的数据项？').then(function() {
    return delTalent(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('article/talent/export', {
    ...queryParams.value
  }, `talent_${new Date().getTime()}.xlsx`)
}

function listOptions() {
  listOptionsCategory({ 
    type: 'TALENT_SERVICE'
  }).then(res => {
    categoryOptions.value = res.data
  })
  listOptionsTag({ type: 'TALENT_SERVICE' }).then(res => {
    tagOptions.value = res.data
  })
  listAllCityWithChildren().then(res => {
    cityOptions.value = res.data
  })
}
function getStatus(row) {
  if (row.status === 'REJECT') {
    return '已驳回'
  } else if (row.status === 'AUDIT') {
    return '已通过'
  } else {
    return '待审核'
  }
}
function getStatusType(row) {
  if (row.status === 'REJECT') {
    return 'danger'
  } else if (row.status === 'AUDIT') {
    return 'success'
  } else {
    return 'info'
  }
}
function handleAudit(row) {
  auditForm.value.id = row.id
  auditForm.value.status = 'NOT_AUDIT'
  isAuidt.value = true
}

function submitAuditForm() {
  auditTalent(auditForm.value).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
    cancel()
  }).catch(() => {});
}
listOptions()
getList();
</script>
